package thread.lock;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决死锁问题
 *
 * @author liweimin
 * @date 2021/5/7 13:51
 * @since
 */
public class Test03 {

    public static void main(String[] args) {
        IntLock intLock = new IntLock(11);
        IntLock intLock1 = new IntLock(22);

        Thread thread = new Thread(intLock);
        thread.start();
        Thread thread1 = new Thread(intLock1);
        thread1.start();

        /*main线程等待3s如果有线程未结束，中断*/
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (thread1.isAlive()) {
            thread1.interrupt();
        }
//        if (thread.isAlive()) {
//            thread.interrupt();
//        }
    }

    static class IntLock implements Runnable {

        public static ReentrantLock lock1 = new ReentrantLock();
        public static ReentrantLock lock2 = new ReentrantLock();

        int lockNum;//决定用哪把锁

        public IntLock(int lockNum) {
            this.lockNum = lockNum;
        }

        @Override
        public void run() {
            try {
                if (lockNum % 2 == 1) {//奇数
                    lock1.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName() + "获得锁1，还需要获得锁2");
                    Thread.sleep(new Random().nextInt(500));
                    lock2.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName() + "同时获得锁1和锁2");
                } else {//偶数
                    lock2.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName() + "获得锁2，还需要获得锁1");
                    Thread.sleep(new Random().nextInt(500));
                    lock1.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName() + "同时获得锁2和锁1");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //被当前线程持有就释放
                if (lock1.isHeldByCurrentThread()) {
                    lock1.unlock();
                }
                if (lock2.isHeldByCurrentThread()) {
                    lock2.unlock();
                }
                System.out.println(Thread.currentThread().getName() + "退出");
            }
        }
    }
}
